package com.bo.baby2.controller;

import com.alibaba.fastjson.JSONArray;
import com.bo.baby2.config.ReturnResult;
import com.bo.baby2.entity.*;
import com.bo.baby2.service.*;
import com.bo.baby2.tools.PageSupport;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @program: baby2_p2p
 * @description: 控制器
 * @author:波
 * @create: 2020-07-12 13:17
 **/
@RestController
@Api(tags = "user信息控制器")
public class UserAccountController {
    @Resource
    private TuserAaccountService tuserAaccountService;
    @Resource
    private UserWallet userWallet;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SystemDictionryItemService systemDictionryItemService;

    @Resource
    private BankCardService bankCardService;

    @Resource
    private WithdrawService withdrawService;
    @Resource
    private AccountFlowMapperService accountFlowMapperService;
    @PostMapping("/user/checkUsername")
    @ApiOperation(value = "根据用户名查询用户是否存在")
    @ApiImplicitParam(value = "用户名")
    /**
     * 判断用户名是否存在
     */
    public boolean checkUsername(HttpServletRequest request,Model model)
    {
        String username = request.getParameter("username");
        Boolean aBoolean=false;
        if (!StringUtils.isEmpty(username)){
             aBoolean = tuserAaccountService.checkUsername(username);
        }
        return aBoolean;
    }

    /**
     * 注册方法
     * @param tUserAccount
     * @return
     */
    @ApiOperation(value = "注册方法")
    @RequestMapping("/user/register")
    @ApiImplicitParam(name="tUserAccount",value = "账户信息实体类")
    public Object register(TUserAccount tUserAccount){
        String id=String.valueOf(System.currentTimeMillis())+Math.round(Math.random()+1*1000);
        System.out.println("id="+id);
        if(!StringUtil.isNullOrEmpty(tUserAccount.getUsername())&&!StringUtil.isNullOrEmpty(tUserAccount.getPassword())) {
            tUserAccount.setId(id);
            tUserAccount.setAccountStatus(0);
            tUserAccount.setAccountType(1);
            Boolean Boolean = tuserAaccountService.insertSelective(tUserAccount);
            if (Boolean) {
                return ReturnResult.successResult("注册成功",null);
            } else {
                return ReturnResult.failResult("注册失败");
            }
        }else {
            return ReturnResult.failResult("数据不完整");
        }
    }

    /**
     * 注销的方法
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("userAccount");
        response.sendRedirect("index.html");
    }

    /**
     * 登录方法
     * @return
     */
    @ApiOperation(value = "登录方法")
    @RequestMapping("/user/login")
    @ApiImplicitParam("账户信息实体类")
    public Object login(TUserAccount tUserAccount,HttpServletRequest request){
        ReturnResult returnResultr=new ReturnResult();
        if(!StringUtil.isNullOrEmpty(tUserAccount.getUsername())&&!StringUtil.isNullOrEmpty(tUserAccount.getPassword())){
            String ip = request.getRemoteAddr();
            returnResultr = tuserAaccountService.login(tUserAccount,ip);
            if(returnResultr.getCode().equals("200")){
                request.getSession().setAttribute("userAccount",returnResultr.getData());
                //登录成功之后放入redis缓存
                /*stringRedisTemplate.opsForValue().set(request.getSession().getId(), JSONArray.toJSONString(returnResultr.getData()),30L, TimeUnit.MINUTES);*/
            }
        }else {
            returnResultr=ReturnResult.failResult("用户名密码不能为空");
        }
        return returnResultr;
    }

    /**
     * 根据id查询账户钱包信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询账户钱包信息")
    @RequestMapping("/user/wallet/get/{id}")
    @ApiImplicitParam(name="id",value = "账号Id")
    public Object getWallet(@PathVariable("id")String id){
        TUserWallet userWallet = null;
        ReturnResult returnResult=null;
        if(!StringUtil.isNullOrEmpty(id)){
            userWallet = this.userWallet.selectByPrimaryKey(id);
            if(userWallet!=null){
                returnResult=ReturnResult.successResult("200",userWallet);
            }else {
                returnResult=ReturnResult.failResult("没有该数据");
            }
        }else {
            returnResult=ReturnResult.failResult("没有该数据");
        }
        return returnResult;
    }

    /**
     * 根据Id查询用户信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据Id查询用户信息")
    @RequestMapping("user/userinfo/get/{id}")
    @ApiImplicitParam(name="id",value = "账号Id")
    public Object getUserInfo(@PathVariable("id")String id){
        ReturnResult returnResult=null;
        if(!StringUtil.isNullOrEmpty(id)){
            TUserInfo tUserInfo =new TUserInfo();
            tUserInfo = userInfoService.selectByPrimaryKey(id);
            if(tUserInfo==null){
                tUserInfo =new TUserInfo();
                tUserInfo.setAvatar("/avatar/nobody.jpg");
            }
            returnResult=ReturnResult.successResult("成功",tUserInfo);
        }else {
            returnResult=ReturnResult.failResult("用户id不能为空");
        }
        return returnResult;
    }

    /**
     * 查询字典所有 内容
     * @return
     */
    @RequestMapping("system/dictionaryItem/getAll")
    public Object getDictionaryItemAll(){

        List<TSystemDictionaryItem> dictionaryAll = systemDictionryItemService.getDictionaryAll();
        ReturnResult returnResult=null;
        if(dictionaryAll.size()>0){
            returnResult=ReturnResult.successResult("查询成功",dictionaryAll);
        }else {
            returnResult=ReturnResult.failResult("没有该数据");
        }
        return returnResult;
    }

    /**
     * 上传头像
     * @param multipartFile
     * @param request
     * @return
     */
    @RequestMapping("/user/userinfo/uploadAvatar")
    public Object uploadAvatar(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request){
        String uploadPath="D:\\y2\\baby2_p2p\\src\\main\\resources\\static\\avatar";     //实际上传路径
        String avatr="avatar";
        if(multipartFile!=null){
            //获取文件名
            String originalFilename = multipartFile.getOriginalFilename();

            String prefix=originalFilename.substring(originalFilename.lastIndexOf("."));//  获取后缀
            List<String> prefixs = Arrays.asList(".jpg", ".png", ".gif", ".jpeg", ".pneg");
            if (!prefixs.contains(prefix)) {
                return ReturnResult.failResult("上传的文件类型不匹配");
            }
            //重新定义文件名
            String filename=System.currentTimeMillis()+Math.abs(new Random().nextLong())+prefix;
            File targetFile=new File(uploadPath,filename);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            try {
                multipartFile.transferTo(targetFile);
                avatr=avatr+File.separator+filename;
            } catch (IOException e) {
                e.printStackTrace();
                return ReturnResult.failResult("上传文件失败");
            }
        }
        return ReturnResult.successResult("上传文件成功",avatr);
    }

    /**
     * 修改用户信息
     * @param tUserInfo
     * @return
     */
    @RequestMapping("user/userinfo/update")
    public Object updateUserinfo(TUserInfo tUserInfo){
        if(tUserInfo!=null){
            return userInfoService.updateByPrimaryKeySelective(tUserInfo);
          /*  if(i>0){
                return ReturnResult.successResult("修改成功",null);
            }else {
                return ReturnResult.failResult("修改失败");
            }*/
        }else {
            return ReturnResult.failResult("数据不能为空");
        }
    }

    /**
     * 根据id查询银行卡信息
     * @param id
     * @return
     */
    @RequestMapping("user/bankcard/get/{id}")
    public Object getBankcard(@PathVariable("id")String id){
        if (!StringUtil.isNullOrEmpty(id)) {
            TBankCard tBankCard = bankCardService.selectByUserId(id);
            if(tBankCard!=null){
                return ReturnResult.successResult(null,tBankCard);
            }else {
                return new ReturnResult("404",null,null);
            }
        }else {
            return ReturnResult.failResult("Id数据不能为空");
        }
    }

    /**
     * 新增银行卡信息
     * @param tBankCard
     * @return
     */
    @RequestMapping("user/bankcard/add")
    public Object addBankcard(TBankCard tBankCard){
        if(tBankCard!=null){
           return bankCardService.insertSelective(tBankCard);
        }else {
            return ReturnResult.failResult("数据不能为空");
        }
    }
    /**
     *提现的方法
     */
    @RequestMapping("/user/withdraw/add")
    public Object addWithdraw(TWithdraw tWithdraw){
        if(tWithdraw!=null){
           return withdrawService.insertSelective(tWithdraw);
        }else {
            return "数据不能为空";
        }
    }

    /**
     * 查询账号流水
     * @param logingLogGet
     * @return
     */
    @RequestMapping("user/accountflow/query")
    public Object getAccountflow(LogingLogGet logingLogGet){
        if(logingLogGet!=null) {
            PageSupport pageSupport = new PageSupport();
            logingLogGet.setPageSize(5);
            logingLogGet.setTotalCount(accountFlowMapperService.getCount(logingLogGet));
            if(StringUtils.isEmpty(logingLogGet.getCurrentPage())){
                logingLogGet.setCurrentPageNo(1);
            }else {
                logingLogGet.setCurrentPageNo(logingLogGet.getCurrentPage());
            }
            List<TAccountFlow> accountFlows = accountFlowMapperService.getAccountFlows(logingLogGet);
            logingLogGet.setListData(accountFlows);
            return ReturnResult.successResult("成",logingLogGet);
        }else {
            return ReturnResult.failResult("数据不能为空");
        }
    }
}
